<?php

namespace app\company\controller\consult\subset;

use app\BaseController;
use app\model\ConsultOfflineModel;
use app\model\ConsultOnlineModel;
use app\model\UnitModel;
use app\model\UserModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }


    /**
     * 主页
     * @return bool|string
     */
    public function Index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'pageSize|每页显示数量' => 'require',
            ]);
            $where = [];
            if (!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }
            $where[] = ['company_id','=',$this->userData['company_id']];
            $where[] = ['areas_id','=',$param['id']];
            $UnitModel = new UnitModel();
            $ConsultOnlineModel = new ConsultOnlineModel();
            $ConsultOfflineModel = new ConsultOfflineModel();
            $UserModel = new UserModel();
            $data = $UnitModel->field('id,name,banner,level,province_name,city_name,area_name')->where($where)->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item){
                $item['online_count'] = $ConsultOnlineModel->where('unit_id','=',$item['id'])->count();
                $item['offline_count'] = $ConsultOfflineModel->where('unit_id','=',$item['id'])->count();
                $item['consult_count'] = $UserModel->where([
                    ['unit_id','=',$item['id']],
                    ['role_mode','=',2]
                ])->count();
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}